﻿using System;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using System.Windows.Forms;

namespace RestfullTest
{
    public partial class FrmRestfull : Form
    {
        public static FrmRestfull Self { set; get; }
        Restfull restfull = new Restfull();

        public FrmRestfull()
        {
            InitializeComponent();
            FrmRestfull.Self = this;
        }

        private void FrmRestfull_Load(object sender, EventArgs e)
        {
            txtBulidMsg.Text = "";
            cbMethod.SelectedIndex = 0;
            cbContentType.SelectedIndex = 0;
        }

        private void btnRun_Click(object sender, EventArgs e)
        {
            restfull.Url = tbUrl.Text.Trim();
            if (restfull.Url == "")
            {
                MessageBox.Show("提示：请输入URL地址！");
                return;
            }

            gbRequest.Enabled = tc.Enabled = false;

            restfull.Method = cbMethod.Text;
            restfull.ContentType = cbContentType.Text;

            if (tc.SelectedTab == tpOne)
            {                
                txtResult.Text = restfull.Query(tbContent.Text.Trim());
            }
            else if (tc.SelectedTab == tpFile)
            {
                txtFileMsg.Text = "";
                foreach (DataGridViewRow row in dgvFile.Rows)
                {
                    var content = row.Cells["dgvcContent"].Value + "";
                    var reg = row.Cells["dgvcReg"].Value + "";
                    var result = restfull.Query(content.Trim());
                    row.Cells["dgvcRes"].Value = result;
                    Regex r = new Regex(reg);
                    bool isReg = r.IsMatch(result);
                    string strResult=isReg ? "成功" : "失败";
                    row.Cells["dgvcResult"].Value = strResult;
                    var msg = string.Format("请求内容:{0}\n正则校验:{1}\n应答结果:{2}\n状态:{3}\n\n", content, reg, result, strResult);
                    txtFileMsg.Text += msg;
                }
            }

            gbRequest.Enabled = tc.Enabled = true;
        }

        private void btnFile_Click(object sender, EventArgs e)
        {
            OpenFileDialog ofd = new OpenFileDialog();
            if (ofd.ShowDialog() == DialogResult.OK)
            {
                dgvFile.Rows.Clear();
                string[] lines = File.ReadAllLines(ofd.FileName);
                LoadLines(lines);
            }
        }

        private void LoadLines(params string[] lines)
        {
            for (int i = 0; i < lines.Length; i += 2)
            {
                dgvFile.Rows.Add();
                var row = dgvFile.Rows[dgvFile.RowCount - 1];
                row.Cells["dgvcContent"].Value = lines[i];
                if (i + 1 < lines.Length) row.Cells["dgvcReg"].Value = lines[i + 1];
                row.Cells["dgvcResult"].Value = "初始化";
            }
        }

        private void tsmHelpContent_Click(object sender, EventArgs e)
        {
            FrmHelp.Print();
        }

        private void tsmAbout_Click(object sender, EventArgs e)
        {
            new FrmAbout().ShowDialog();
        }

        private void tbBulider_TextChanged(object sender, EventArgs e)
        {
            txtBulidMsg.Text = "";
            rtbBuliderOutput.Text = "";
            var parLines = rtbBuliderParams.Text.Split('\n');
            foreach (var parLine in parLines)
            {
                var pars = parLine.Split(',');
                if (rtbBuliderOutput.Text != "") rtbBuliderOutput.Text += '\n';
                try { rtbBuliderOutput.Text += string.Format(rtbBuliderInput.Text, pars); }
                catch { rtbBuliderOutput.Text += rtbBuliderInput.Text; }
            }
        }

        private void btnBulidCopy_Click(object sender, EventArgs e)
        {
            Clipboard.SetText(rtbBuliderOutput.Text);
            txtBulidMsg.Text = "提示：已复制！";
        }

        private void btnBulidSave_Click(object sender, EventArgs e)
        {
            SaveFileDialog sfd = new SaveFileDialog();
            if (sfd.ShowDialog() == DialogResult.OK)
            {
                try
                {
                    File.WriteAllText(sfd.FileName, rtbBuliderOutput.Text.Replace("\n",Environment.NewLine));
                    txtBulidMsg.Text = "提示：保存成功！";
                }
                catch(Exception ex)
                {
                    txtBulidMsg.Text = "提示：保存失败！信息：" + ex.Message;
                }
            }
            else txtBulidMsg.Text = "提示：已取消保存！";
        }

        private void btnBulidLoad_Click(object sender, EventArgs e)
        {
            var lines = rtbBuliderOutput.Text.Split('\n');
            LoadLines(lines);
            tc.SelectedTab = tpFile;
        }

        private void tsmFileClear_Click(object sender, EventArgs e)
        {
            dgvFile.Rows.Clear();
        }

        private void tsmFileAdd_Click(object sender, EventArgs e)
        {
            dgvFile.Rows.Add();
        }

        private void cmsFile_Opening(object sender, System.ComponentModel.CancelEventArgs e)
        {
            foreach (ToolStripMenuItem item in cmsFile.Items) item.Enabled = true;
        }

        private DataGridView.HitTestInfo GetHit()
        {
            var point = dgvFile.PointToClient(Control.MousePosition);
            var hit = dgvFile.HitTest(point.X, point.Y);
            return hit;
        }

        private void cmsFile_Opened(object sender, EventArgs e)
        {
            if (dgvFile.Rows.Count <= 0) tsmFileClear.Enabled = false;
            var hit = GetHit();
            if (hit.RowIndex < 0 || hit.ColumnIndex < 0) tsmFileDelete.Enabled = false;
            else tsmFileDelete.Tag = hit;
        }

        private void tsmFileDelete_Click(object sender, EventArgs e)
        {
            var hit = tsmFileDelete.Tag as DataGridView.HitTestInfo;
            if (hit == null) return;
            dgvFile.Rows.RemoveAt(hit.RowIndex);
        }

        private void tc_SelectedIndexChanged(object sender, EventArgs e)
        {
            btnRun.Enabled = tc.SelectedTab!=tpBulider;
        }
    }
}
